package hello

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logc"
	"go.zero.learn/internal/svc"
	"go.zero.learn/internal/types"
	model "go.zero.learn/model/mongodb"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
	"go.zero.learn/internal/entity/user"
)

type HelloPingLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewHelloPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HelloPingLogic {
	return &HelloPingLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *HelloPingLogic) HelloPing(req *types.PingReq) (resp *types.PingResp, err error) {
	// todo: add your logic here and delete this line

	// 测试 中间件取值
	fmt.Println("--------")
	fmt.Println(l.ctx.Value("User-Agent"))
	fmt.Println("---------")

	var data user.UserEntity

	// 读取 数据库数据
	result := l.svcCtx.GormDb.Where("name=? and password=?", "admin", "123").First(&data)

	if result.Error != nil {
		return &types.PingResp{Message: "hello:" + req.Name}, result.Error
	}

	fmt.Println("--------")
	fmt.Println(data.Name + "-------" + data.Password)
	fmt.Println("---------")

	// 测试 日志
	logc.Info(l.ctx, "测试日志")
	logx.Info("测试日志2")

	// 向 mongodb 写入数据
	errMongo := l.svcCtx.MongoDb.Insert(l.ctx, &model.Testmongodb{Name: "PengW", UpdateAt: time.Now(), CreateAt: time.Now()})
	if errMongo != nil {
		logc.Error(l.ctx, errMongo)
	}

	return &types.PingResp{Message: "hello:" + req.Name + "数据库取值：" + data.Name}, nil
}
